*===================================================================*
* Calculates Quantiles in EPH                                                    *
*===================================================================*


capture program drop cuantiles

program define cuantiles
  version 7.0
  syntax varlist(max=1) [if] [fweight], Ncuantiles(integer) Generate(namelist) [orden_aux(varlist)]
  tokenize `varlist'
  
  quietly {

    *Quantiles in, for example, d_ipcf
    local quanpers="`generate'"
    
    tempvar suma mipondera mivar
  
    local wt : word 2 of `exp'
    if "`wt'"=="" {
      local wt = 1
    }  

    gen `mivar'=.
    replace `mivar'=`1' `if' 

    replace `mivar'=. if `1'==.

    sort `mivar' `orden_aux', stable
    
    gen `mipondera'=`wt'
    replace `mipondera'=0 if `mivar'==.     
    gen `suma'=sum(`mipondera')

    *ppquan = Number of people per quantil
    *ppquan is Number of people that should be in each quantile 

    summ `mipondera', meanonly
    
    scalar ppquan = r(sum)/`ncuantiles'
    generate `quanpers'=.
    
    forvalues i=1(1)`ncuantiles' {
      display `i'
      replace `quanpers'=`i' if `suma'>(`i'-1)*ppquan & `suma'<=`i'*ppquan & `mivar'!=. 
    }
 
  }
  
  if `ncuantiles' <=375 { 
    tabulate `quanpers' [`weight'`exp'], summ(`1')
  }
end




